<template>
  <div class="login">
    <!-- 头部导航条 -->
    <van-nav-bar title="登录" />

    <!--
  登录表单
  点击登录按钮的时候，会触发submit事件
  -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        label="手机号"
        placeholder="请输入你的手机号"
        :rules="rules.mobile"
        required
      />
      <van-field
        v-model="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
        required
      />
      <div style="margin: 16px;">
        <van-button
          :disabled="loading"
          :loading="loading"
          loading-text="加载中..."
          round
          block
          type="info"
          native-type="submit"
        >
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      mobile: '13912345678',
      code: '246810',
      rules: {
        mobile: [
          {
            required: true,
            message: '手机号不能为空',
            trigger: 'onBlur'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误',
            trigger: 'onBlur'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空',
            trigger: 'onBlur'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误',
            trigger: 'onBlur'
          }
        ]
      },
      loading: false
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async onSubmit() {
      this.loading = true
      try {
        const res = await userLogin(this.mobile, this.code)
        this.$toast.success('登录成功')
        // 保存token
        // this.$store.commit('setToken', res.data.data)
        this.setToken(res.data.data)
        if (this.$route.query.goBack) {
          // 回退
          this.$router.back()
        } else {
          const back = this.$route.query.back || '/'
          this.$router.push(back)
        }
        // if (this.$route.query.back) {
        //   // 如果有back参数，需要跳回去
        //   this.$router.push(this.$route.query.back)
        // } else {
        //   this.$router.push('/')
        // }
      } catch (err) {
        this.$toast.fail('登录失败')
      }
      this.loading = false
    }
  }
}
</script>

<style></style>
